<template>
  <div class="question_new-container">
    <el-card class="wrap">
      <!-- 标题 -->
      <el-row class="title-wrap">
        <h2 class="title">试题录入</h2>
      </el-row>
      <!-- /标题 -->
      <!-- <el-divider></el-divider> -->
      <el-form
        :model="questionForm"
        :rules="questionFormRules"
        ref="questionFormRef"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            v-model="questionForm.subjectID"
            placeholder="请选择"
            @change="questionForm.catalogID = null"
          >
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="目录:" prop="catalogID">
          <el-select
            v-model="questionForm.catalogID"
            placeholder="请选择"
            @focus="loadDirectorys"
          >
            <el-option
              v-for="item in directoryOptions"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID" required>
          <el-select v-model="questionForm.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="province" required class="city">
          <!-- 城市列表 -->
          <el-select
            v-model="questionForm.province"
            placeholder="请选择"
            @focus="loadCityList"
            @change="questionForm.city = ''"
          >
            <el-option
              v-for="(city, index) in cityList"
              :key="index"
              :label="city"
              :value="city"
            >
            </el-option>
          </el-select>
          <!-- /城市列表 -->
          <!-- 县级市列表 -->
          <el-select
            v-model="questionForm.city"
            placeholder="请选择"
            @focus="loadCountyList"
          >
            <el-option
              v-for="(county, index) in countyList"
              :key="index"
              :label="county"
              :value="county"
            >
            </el-option>
          </el-select>
          <!-- /县级市列表 -->
        </el-form-item>
        <el-form-item label="方向:" prop="direction" required>
          <el-select
            v-model="questionForm.direction"
            placeholder="请选择"
            @focus="loadDirectionList"
          >
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" required class="topic">
          <el-radio-group v-model="questionForm.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" required class="difficulty">
          <el-radio-group v-model="questionForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <!-- 富文本编辑器 -->
          <quill-editor
            ref="myQuillEditor"
            v-model="questionForm.question"
            :options="editorOption"
          ></quill-editor>
          <!-- /富文本编辑器 -->
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项:" v-if="isOptionsShow" required>
          <el-checkbox-group v-model="checkList">
            <el-radio-group v-model="radio" class="option">
              <el-row v-for="(item, index) in count" :key="index">
                <el-radio v-if="isRadio" :label="option[index]"
                  >{{ option[index] }}:</el-radio
                >
                <el-checkbox v-else :label="option[index]"
                  >{{ option[index] }}:</el-checkbox
                >
                <el-input v-model="options[option[index]]"></el-input>
                <i
                  class="el-icon-circle-close"
                  @click="
                    (res, file) => {
                      removePhoto(index, res, file)
                    }
                  "
                ></i>
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:3001/upload"
                  :on-success="
                    (res, file) => {
                      handleAvatarSuccess(index, res, file)
                    }
                  "
                  :on-remove="
                    (res, file) => {
                      removePhoto(index, res, file)
                    }
                  "
                  :on-preview="previewPhoto"
                >
                  <img
                    v-if="imageUrl[index]"
                    :src="imageUrl[index]"
                    class="avatar"
                  />
                  <div v-else>
                    <span class="post">上传图片</span>
                  </div>
                </el-upload>
              </el-row>
            </el-radio-group>
          </el-checkbox-group>
          <!-- 按钮 -->
          <el-row>
            <el-button
              type="danger"
              class="danger"
              size="small"
              :disabled="isDisabled"
              @click="addOption"
              ><span>+增加选项与答案</span></el-button
            ></el-row
          >
          <!-- /按钮 -->
        </el-form-item>
        <!-- /选项 -->
        <!-- 解析视频 -->
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input
            v-model="questionForm.videoURL"
            class="inputVideo"
          ></el-input>
        </el-form-item>
        <!-- /解析视频 -->
        <!-- 答案解析 -->
        <el-form-item label="答案解析:" prop="answer">
          <!-- 富文本编辑器 -->
          <quill-editor
            ref="myQuillEditor"
            v-model="questionForm.answer"
            :options="editorOption"
          ></quill-editor>
          <!-- /富文本编辑器 -->
        </el-form-item>
        <!-- /答案解析 -->
        <!-- 题目备注 -->
        <el-form-item label="题目备注" prop="remarks">
          <el-input
            type="textarea"
            v-model="questionForm.remarks"
            class="textarea"
          >
          </el-input>
        </el-form-item>
        <!-- /题目备注 -->
        <!-- 试题标签 -->
        <el-form-item label="试题标签:" prop="tags">
          <el-select
            v-model="questionForm.tags"
            multiple
            filterable
            allow-create
            default-first-optionplaceholder="请选择试题标签"
          >
            <el-option
              v-for="item in tagList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- /试题标签 -->
        <!-- 确认提交 -->
        <el-form-item label="" required>
          <el-button type="primary" @click="onSubmit">确认提交</el-button>
        </el-form-item>
        <!-- /确认提交 -->
      </el-form>
    </el-card>
    <!-- 图片预览 -->

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import { simple as tagList } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import { list as directorysList } from '@/api/hmmm/directorys'
import { list as companyList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'
import hljs from 'highlight.js'
import 'highlight.js/styles/dracula.css'
export default {
  name: 'QuestionNew',
  data() {
    return {
      questionForm: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: '', // 县
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 富文本编辑器内容
        tags: [], // 试题标签
        options: [], // 选项
        videoUrl: null, // 解析视频
        answer: null, // 答案解析
        remarks: null // 题目备注
      },
      questionFormRules: {
        subjectID: [{ required: true, message: '请输入学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请输入目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请输入企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请输入城市', trigger: 'blur' }],
        direction: [{ required: true, message: '请输入方向', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入题目备注', trigger: 'blur' }
        ],
        tags: [{ required: true, message: '请输入试题标签', trigger: 'blur' }]
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote'], // 引用，代码块
            ['code-block', 'image', 'link'] // 图片 链接
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        },
        placeholder: ''
      },
      // 选项
      options: {
        A: '',
        B: '',
        C: '',
        D: ''
      },
      checkList: [], // 选中的数组
      radio: '',
      radioList: ['A', 'B', 'C', 'D'],
      count: 4,
      option: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
      // 上传图片地址
      imageUrl: [],
      parsingVideo: '', // 解析视频
      textarea: '', // 题目备注
      subjectOptions: [], // 学科列表
      directoryOptions: [], // 目录列表
      companyList: [], // 企业列表
      cityList: [], // 城市列表
      countyList: [], // 地级市列表
      directionList: [], // 方向列表
      isDisabled: true, // 禁用按钮
      isOptionsShow: true, // 控制选项是否渲染
      tagList: [], // 试题标签列表
      previewVisible: false, // 图片预览显示隐藏
      previewPath: '', // 图片路径
      questionId: null, // 问题id
      tempId: null, // 临时id
      isRadio: true // 单选
    }
  },
  methods: {
    // 头像上传成功触发的钩子
    handleAvatarSuccess(index, res, file) {
      // this.imageUrl.splice(index, 1, 'http://localhost:3001/' + res.url)
      this.imageUrl[index] = 'http://localhost:3001/' + res.url
      this.imageUrl.splice(index, 1, 'http://localhost:3001/' + res.url)
    }, // 文件上传成功
    // 删除图片
    removePhoto(index, res, file) {
      this.imageUrl.splice(index, 1, '')
      this.$message.success('删除图片成功')
    },
    // 预览
    previewPhoto(file) {
      this.previewVisible = true
      this.previewPath = 'http://localhost:3001/' + file.response.url
    }, // 预览

    // 加载学科列表
    async loadSubjects() {
      try {
        const { data } = await simple()
        this.subjectOptions = data
      } catch (err) {
        this.$message.error('加载学科列表失败,请稍后再试')
      }
    },
    // 加载学科目录
    async loadDirectorys() {
      try {
        if (!this.questionForm.subjectID) {
          this.questionForm.directoryOptions = ''
        } else {
          const { data } = await directorysList({
            subjectID: this.questionForm.subjectID
          })
          this.directoryOptions = data.items
        }
      } catch (err) {
        this.$message.error('加载目录列表失败,请稍后再试')
      }
    },
    // 加载企业列表
    async loadCompanyList() {
      try {
        const { data } = await companyList({
          pagesize: 100
        })
        this.companyList = data.items
      } catch (err) {
        this.$message.error('加载企业列表失败,请稍后再试')
      }
    },
    // 加载城市列表
    loadCityList() {
      try {
        const data = provinces()
        this.cityList = data
      } catch (err) {
        this.$message.error('加载城市列表失败,请稍后再试')
      }
    },
    // 加载县级市列表
    loadCountyList() {
      try {
        const data = citys(this.questionForm.province)
        this.countyList = data
      } catch (err) {
        this.$message.error('加载地级市列表失败,请稍后再试')
      }
    },
    // 加载方向列表
    loadDirectionList() {
      this.directionList = direction
    },
    // 加载试题标签
    async loadTags() {
      try {
        const { data } = await tagList({
          subjectID: this.questionForm.subjectID
        })
        this.tagList = data
      } catch (err) {
        this.$message.error('加载试题标签失败,请稍后再试')
      }
    },
    // 按钮变化(单选多选)
    // topicChange() {
    //   if (this.questionForm.questionType === '1') {
    //     this.isOptionsShow = true
    //     this.isDisabled = true
    //     this.questionForm.options = ''
    //   } else if (this.questionForm.questionType === '2') {
    //     this.isOptionsShow = true
    //     this.isDisabled = false
    //     this.questionForm.checkList = []
    //   } else {
    //     this.isOptionsShow = false
    //   }
    // },
    // 增加选项
    addOption() {
      if (this.count >= 10) {
        this.$message.warning('每个题目最多只能有10个选项哦')
        this.isDisabled = true
      } else {
        this.count++
      }
    },
    // 确认提交
    async onSubmit() {
      this.$refs.questionFormRef.validate(valid => {
        if (!valid) {
          this.$message.error('请填入符合规则的内容')
          // this.$refs.questionFormRef.resetFields()
        } else {
          if (this.questionForm.questionType === '1') {
            if (!this.radio) return this.$message.error('单选题至少选一项')
          } else if (this.questionForm.questionType === '2') {
            if (this.checkList.length <= 1) { return this.$message.error('多选题至少选两项') }
          } else {
            this.options = {}
          }
          for (const k in this.options) {
            if (this.options[k].trim().length === 0) {
              return this.$message.error('选项内容不能为空')
            }
            // console.log(this.options[k].length)
          }
          if (this.questionForm.city.trim().length === 0) { return this.$message.error('请填入地名') }
          // 处理试题标签
          this.questionForm.tags = this.questionForm.tags.join()
          if (this.questionId) {
            // 编辑
            this.editQuestion()
          } else {
            // 添加
            this.addQuestion()
          }
          this.$router.push(this.$route.query.redirect || '/questions/list')
          console.log(this.questionForm)
        }
      })
    },
    // 提交前处理数据
    processData() {
      this.questionForm.options = []
      if (this.questionForm.questionType === '1') {
        // 单选
        for (let i = 0; i < this.radioList.length; i++) {
          this.questionForm.options.push({
            code: this.radioList[i],
            title: this.options[this.option[i]],
            img: this.imageUrl[i],
            isRight: this.radio === this.radioList[i]
          })
        }
      } else if (this.questionForm.questionType === '2') {
        // 多选
        for (let i = 0; i < this.allCheckList.length; i++) {
          this.questionForm.options.push({
            code: this.allCheckList[i],
            title: this.options[this.option[i]],
            img: this.imageUrl[i],
            isRight: this.checkList.includes(this.allCheckList[i])
          })
        }
      }
    },
    // 添加问题
    async addQuestion() {
      try {
        this.processData()
        await add(this.questionForm)
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.questionForm.options = []
      } catch (err) {
        this.$message({
          message: '添加失败',
          type: 'error'
        })
      }
    },
    // 编辑问题
    async editQuestion() {
      this.processData()
      this.questionForm.id = parseInt(this.questionId)
      if (typeof this.questionForm.catalogID === 'string') {
        this.questionForm.catalogID = this.tempId
      }
      try {
        await update(this.questionForm)
        this.$message.success('修改成功')
        console.log(this.questionForm)
      } catch (err) {
        this.$message.error('修改失败')
      }
    },
    // 根据id查题目详情
    async getQuestion() {
      const { data } = await detail({
        id: this.questionId
      })
      console.log(data)
      // 获取后处理数据
      this.questionForm = data
      this.tempId = data.catalogID
      this.questionForm.catalogID = data.directoryName
      // 如果有选项
      if (this.questionForm.options) {
        if (this.questionForm.questionType === '1') {
          // 单选
          const rightItem = this.questionForm.options.find(item => item.isRight)
          this.radio = rightItem && rightItem.code
        } else if (this.questionForm.questionType === '2') {
          // 多选
          const checkedArr = []
          this.questionForm.options.forEach(item => {
            if (item.isRight === 1) {
              checkedArr.push(item.code)
            }
          })
          this.checkList = checkedArr
        }

        this.questionForm.tags = this.questionForm.tags.split(',')
        this.tagList = this.questionForm.tags

        this.$nextTick(() => {
          for (let i = 0; i <= this.allCheckList.length; i++) {
            this.questionForm.options.forEach(item => {
              if (item.code === this.allCheckList[i]) {
                this.imageUrl.push(item.img)
              }
            })
          }
          this.questionForm.options.forEach(item => {
            console.log(item.title)
            this.$set(this.options, item.code, item.title)
            // const newArr = JSON.parse(JSON.stringify(this.options))
            // newArr[item.code] = item.title
            // this.options = newArr
          })
        })
      }
      // console.log(this.questionForm)
    }
  },
  created() {
    this.loadSubjects()
    this.loadCompanyList()
    if (this.$route.query.id) {
      this.questionId = this.$route.query.id
      this.getQuestion()
    }
  },
  computed: {
    allCheckList() {
      const arr = []
      for (let i = 0; i < this.count; i++) {
        arr.push(this.option[i])
      }
      return arr
    }
  },
  watch: {
    // 监听学科变化
    'questionForm.subjectID': {
      handler() {
        this.loadTags()
      }
    },
    // 题型变化
    'questionForm.questionType': {
      handler() {
        if (this.questionForm.questionType === '1') {
          this.isOptionsShow = true
          this.isDisabled = true
          this.isRadio = true
          this.count = 4
          this.questionForm.options = ''
        } else if (this.questionForm.questionType === '2') {
          this.isOptionsShow = true
          this.isDisabled = false
          this.isRadio = false
          this.questionForm.checkList = []
          if (this.questionForm.options.length >= this.count) {
            this.count = this.questionForm.options.length
          }
        } else {
          this.isOptionsShow = false
        }
      }
    },
    // 监听所有选项变化
    allCheckList() {
      if (this.questionForm.questionType === '1') {
        const reg = /^[EFGHIJ]$/
        for (const k in this.options) {
          if (reg.test(k)) {
            delete this.options[k]
          }
        }
      } else if (this.questionForm.questionType === '2') {
        if (this.count > 4) {
          this.$set(this.options, this.option[this.count - 1], '')
        }
      }
    }
  }
}
</script>

<style scoped>
.question_new-container {
  padding: 20px;
}
.question_new-container .title {
  font-size: 16px;
  font-weight: normal;
  margin: unset;
}
.title-wrap {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
}
.el-divider {
  margin-top: 0;
}
.wrap >>> .el-card__body {
  padding: 0;
}
.el-form {
  padding: 20px;
}
.el-select {
  width: 400px;
  height: 36px;
}
.el-form-item >>> .el-form-item__label {
  padding-right: 20px;
}
.quill-editor >>> .ql-toolbar {
  padding: 0 8px;
}
.quill-editor >>> .ql-editor {
  height: 200px;
}
.option >>> .el-input {
  width: 240px;
}
.el-radio {
  margin-right: 10px;
}
.el-checkbox {
  margin-right: 10px;
}
.avatar-uploader {
  position: relative;
  margin-left: 4px;
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  top: -5px;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar-uploader >>> .el-upload-list {
  position: absolute;
  right: -150px;
  top: 8px;
}
.option .el-row {
  margin-bottom: 20px;
}
.post {
  font-size: 14px;
}
.option >>> .el-row {
  position: relative;
}
.el-row >>> .el-icon-circle-close {
  position: absolute;
  right: -10px;
  top: -10px;
  font-size: 20px;
  color: #999;
}
.danger span {
  font-size: 12px;
}
.inputVideo {
  width: 400px;
}
.textarea >>> .el-textarea__inner {
  width: 400px;
  height: 99px;
  min-height: 33px;
}
.city .el-select {
  width: 198px;
}
.city .el-select:nth-child(1) {
  margin-right: 4px;
}
.avatar {
  width: 88px;
  height: 58px;
}
.topic >>> .el-radio,
.difficulty >>> .el-radio {
  margin-right: 25px;
}
.previewImg {
  width: 90%;
}
</style>
